/*
 * @Author: LiYuan
 * @Date: 2021-03-19 10:43:57
 * @LastEditTime: 2021-06-22 15:15:41
 * @LastEditors: LiYuan
 * @Description:
 * You build it, You run it.
 */
// http://dev.icsoc.net/docs/develop/cti-js-sdk/cti-js-sdk-start/
import { getRootWindow } from '@src/util/dom';
import platform from '../platform';
// import * as TaskApi from '@src/api/TaskApi.ts';
import { agentGetCost } from '@src/api/CallCenterApi.js';
import { t } from '@src/locales'

const RootWindow = getRootWindow(window)

async function judge() {
  const isInit = isCtiSdkInit()
  const isSupportAduio = await judegeSupportAudio()
  return isInit && isSupportAduio
}

// 判断SDK是否初始化
function isCtiSdkInit() {
  if(RootWindow.CTI) {
    return true
  } else {
    console.warn('没有初始化CTI SDK')
    platform.notification({
      title: t('common.base.toast'),
      message: t('system.callCenter.text1'),
      type: 'error',
    })
    return false
  }
}

// 判断是否有麦克风权限
function judegeSupportAudio() {
  navigator.getUserMedia  = navigator.getUserMedia ||
                          navigator.webkitGetUserMedia ||
                          navigator.mozGetUserMedia ||
                          navigator.msGetUserMedia;
  return new Promise((resolve, reject) => {
    if(navigator.getUserMedia) { // 支持
      navigator.getUserMedia(
        { audio:true },
        function onSuccess(stream) {
          resolve(true)
        },
        function onError(error) {
          platform.notification({
            title: t('common.base.toast'),
            message: t('system.callCenter.text2'),
            type: 'error',
          })
          resolve(false)
        });
    } else { // 不支持
      resolve(false)
    }
  })
}

// 外呼
export async function ctiCallOut(tel) {
  if (!await judge()) return
  const {code, message} = await agentGetCost()
  if(code !== 0) {
    platform.notification({
      title: t('common.base.toast'),
      message: message,
      type: 'error',
    })
    return
  }
  const config = RootWindow.CTI.config.getState()
  const params = {
    agPho: config.agentPhone,
    tel
  }
  RootWindow.CTI.Agent.callOut(params, res => {
    if(res.code === 0) {
      console.log('callOut succ', res)
    } else {
      const params = {
        type: 'ctiCallOut',
        code: res.code,
        message: res.message,
        title: t('system.callCenter.text3'),
        payload: tel
      }
      ctiErrorNotice(params, ctiCallOut);
    }
  })

  // const { code, message } = await TaskApi.dialout({phone, taskType:'customer'}, false)
  // if (code !== 0) return platform.notification({
  //   title: '呼出失败',
  //   message: message || '',
  //   type: 'error',
  // })
}

// 外呼取消
export async function ctiCallOutCancel() {
  if (!await judge()) return
  RootWindow.CTI.Session.callOutCancel(res => {
    if(res.code === 0) {
      console.log('callOutCancel succ', res)
    } else {
      const params = {
        type: 'ctiCallOutCancel',
        code: res.code,
        message: res.message,
        title: t('common.base.toast'),
      }
      ctiErrorNotice(params, ctiCallOutCancel);
    }
  })
}

// 接听
export async function ctiSipAnswer(isMicroSip = false) {
  if(isMicroSip){
    platform.notification({
      title: t('common.base.toast'),
      message: t('system.callCenter.text4'),
      type: 'warning',
    })
    return
  }
  if (!await judge()) return 
  RootWindow.CTI.SipPhone.sipAnswer()
}

// 拒接
export async function ctiRefuse() {
  if (!await judge()) return
  RootWindow.CTI.Session.refuse(res => {
    if(res.code === 0) {
      console.log('refuse succ', res)
    } else {
      const params = {
        type: 'ctiRefuse',
        code: res.code,
        message: res.message,
        title: t('common.base.toast'),
      }
      ctiErrorNotice(params, ctiRefuse);
    }
  })
}

// 挂断
export async function ctiHangup() {
  if (!await judge()) return
  RootWindow.CTI.Session.hangup(res => {
    if(res.code === 0) {
      console.log('hangup succ', res)
    } else {
      const params = {
        type: 'ctiHangup',
        code: res.code,
        message: res.message,
        title: t('common.base.toast'),
      }
      ctiErrorNotice(params, ctiHangup);
    }
  })
}

// 签入
export async function ctiLogin() {
  if (!await judge()) return
  const agentPhone = RootWindow.CTI.config.getState().agentPhone
  const loginParam = {
    bindTel: agentPhone
  }
  RootWindow.CTI.Agent.login(loginParam, res => {
    if(res.code === 0) {
      console.log('login succ', res)
    } else {
      console.error(res.message || 'CTI SDK 签入失败')
    }
  })
}

// 签出
export async function ctiLogout() {
  if (!await judge()) return
  RootWindow.CTI.Agent.logout({}, res => {
     if(res.code === 0) {
      console.log('logout succ', res)
     } else {
       console.error(res.message || 'CTI SDK 签出失败')
     }
   })
}

// 咨询转移
export async function ctiConsultTransfer(params ={}) {
  if (!await judge()) return
  console.log(params)
  return new Promise((resolve,reject)=>{
    RootWindow.CTI.Session.consultTransfer(params, res => {
      console.log(res,'咨询转移')
       if(res.code === 0) {
        resolve(true)
       } else {
        reject(res.message || t('system.callCenter.text5'))
       }
     })
  })
}

// 咨询坐席
export async function ctiConsultAg(params ={}) {
  if (!await judge()) return
  return new Promise((resolve,reject)=>{
    RootWindow.CTI.Session.consultAg(params, res => {
      console.log(res,'咨询坐席')
       if(res.code === 0) {
        resolve(true)
       } else {
        reject(res.message || t('system.callCenter.text6'))
       }
     })
  })
}

// 咨询接回
export async function ctiConsultReturn(params ={}) {
  if (!await judge()) return
  console.log(params)
  return new Promise((resolve,reject)=>{
    RootWindow.CTI.Session.consultReturn(params, res => {
      console.log(res,'咨询接回')
       if(res.code === 0) {
        resolve(true)
       } else {
        reject(res.message || t('system.callCenter.text7'))
       }
     })
  })
}

/**
 * @description: 调用SDK方法错误提示
 * @param {Object} params
 * @param {Function} callback
 */
async function ctiErrorNotice(params, callback) {
  const { type, code, message, title = t('common.base.toast'), payload=''} = params
  console.warn(`${type}_errorCode: ${code}`)
  
  // code 5002 token失效
  if(code == 5002) {
    await window.CTI.updateCtiSdkToken()
    callback(payload)
  } else {
    platform.notification({
      title,
      message,
      type: 'error',
    })
  }
}